package com.enlorenz.core.channel.activemq.topic;

import java.util.ArrayList;
import java.util.List;

import javax.jms.ConnectionFactory;

import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.jms.listener.AbstractJmsListeningContainer;
import org.springframework.jms.listener.DefaultMessageListenerContainer;

import com.enlorenz.common.util.DataDetUtils;
import com.enlorenz.common.util.StringUtils;

/**
 * MQ主题事件监听器
 * @author Karma
 */
public class MqTopicListener {
	//主题参数列表
	private List<MqTopicParam> topicParamList;
	//jms容器列表
	private List<AbstractJmsListeningContainer> containerList;
	//jms连接工厂
	private ConnectionFactory connectionFactory;
	
	/**
	 * 初始化主题
	 */
	public void init() {
		if (this.connectionFactory == null) {
			throw new IllegalStateException("jms连接工厂不能为空");
		}

		if (DataDetUtils.isCollectionEmpty(topicParamList)) {
			throw new IllegalStateException("主题列表不能为空");
		}
		
		containerList=new ArrayList<AbstractJmsListeningContainer>(topicParamList.size());
		
		for (MqTopicParam param : topicParamList) {
			if (DataDetUtils.isStrEmpty(param.getClientId())) {
				throw new IllegalStateException("clientId不能为空");
			}
			if (DataDetUtils.isStrEmpty(param.getTopicName())) {
				throw new IllegalStateException("topicName不能为空");
			}
			if (null == param.getMqEventReader()) {
				throw new IllegalStateException("topicEventListener不能为空");
			}
			
			DefaultMessageListenerContainer listener = new DefaultMessageListenerContainer();
			listener.setAutoStartup(false);
			listener.setConnectionFactory(connectionFactory);
			listener.setClientId(param.getClientId());
			listener.setDestination(new ActiveMQTopic(param.getTopicName()));
			listener.setSubscriptionDurable(param.isAcceptOffline());
			listener.setMessageListener(new MqMsgListener(param.getMqEventReader()));
			
			if (!DataDetUtils.isStrEmpty(param.getSubscriptionName())) {
				listener.setDurableSubscriptionName(StringUtils
						.trim(param.getSubscriptionName()));
			}
			if (!DataDetUtils.isStrEmpty(param.getEventNameSelector())) {
				listener.setMessageSelector("eventName='"
						+ StringUtils.trim(param.getEventNameSelector()) + "'");
			}
			
			listener.initialize();
			listener.start();
			
			containerList.add(listener);
		}

	}
	
	/**
	 * 摧毁jms容器
	 */
	public void destroy() {
		for(AbstractJmsListeningContainer listener:containerList){
			listener.destroy();
		}
	}

	public ConnectionFactory getConnectionFactory() {
		return this.connectionFactory;
	}

	public void setConnectionFactory(ConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
	}

	public void setTopicParamList(List<MqTopicParam> topicParamList) {
		this.topicParamList = topicParamList;
	}

	
}